import { Injectable } from "@nestjs/common";
import axios from "axios";

interface IFanyiParams {
  source_language: string;
  target_language: string;
  text: string;
}

@Injectable()
export class TranslateService {
  async getAccessToken() {
    try {
      const res = await axios({
        method: "post",
        url: "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
        data: JSON.stringify({
          app_id: process.env.FEISHU_TRANSLATE_APP_ID,
          app_secret: process.env.FEISHU_TRANSLATE_APP_SECRET,
        }),
        headers: {
          "Content-Type": "application/json; charset=utf-8",
        },
      });
      if (res.status === 200 && res.data.tenant_access_token) {
        return res.data.tenant_access_token;
      } else {
        return Promise.reject(res.data);
      }
    } catch (err) {
      console.log("err: ", err);
      return Promise.reject(err);
    }
  }
  async fanyi(params: IFanyiParams) {
    console.log("params: ", params);
    try {
      const accessToken = await this.getAccessToken();
      const res = await axios({
        method: "post",
        url: "https://open.feishu.cn/open-apis/translation/v1/text/translate",
        data: JSON.stringify(params),
        headers: {
          Authorization: "Bearer " + accessToken,
          "Content-Type": "application/json; charset=utf-8",
        },
      });
      console.log("res: ", res.data);
      if (res.status === 200) {
        return {
          code: 200,
          message: "调用翻译api成功",
          data: res.data.data,
        };
      } else {
        return {
          code: 400,
          message: "调用翻译api失败",
          data: res.data,
        };
      }
    } catch (err: any) {
      console.log("err:1 ", err?.response.data);
      return {
        code: 400,
        message: "调用翻译api失败",
        data: err,
      };
    }
  }
}
